package com.flyco.modules.sms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.modules.sms.entity.SmsCouponHistory;
import com.flyco.modules.sms.mapper.SmsCouponHistoryMapper;
import com.flyco.modules.sms.service.ISmsCouponHistoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * @Description: 优惠券记录
 * @Author: flyco
 * @Date:   2020-01-07
 * @Version: V1.0
 */
@Service
public class SmsCouponHistoryServiceImpl extends ServiceImpl<SmsCouponHistoryMapper, SmsCouponHistory> implements ISmsCouponHistoryService {
	
	@Autowired
	private SmsCouponHistoryMapper smsCouponHistoryMapper;
	
	@Override
	public List<SmsCouponHistory> selectByMainId(Long mainId) {
		return smsCouponHistoryMapper.selectByMainId(mainId);
	}

	@Override
	public SmsCouponHistory selectByCouponCode(String couponCode) {
		LambdaQueryWrapper<SmsCouponHistory> query = new LambdaQueryWrapper<>();
		query.eq(SmsCouponHistory::getCouponCode, couponCode);
		return this.getOne(query,false);
	}

	@Override
	@Transactional
	public void updateCouponStatus(String orderId, Integer useStatus) {
		LambdaQueryWrapper<SmsCouponHistory> query = new LambdaQueryWrapper<>();
		query.eq(SmsCouponHistory::getOrderId, orderId);
		query.eq(SmsCouponHistory::getUseStatus, useStatus == 0 ? 1 : 0);
		List<SmsCouponHistory> couponHistories = this.list(query);
		List<SmsCouponHistory> changeHistorys = new ArrayList<>();
		for ( SmsCouponHistory history : couponHistories ) {
			SmsCouponHistory changeHistory = new SmsCouponHistory();
			changeHistory.setId(history.getId());
			changeHistory.setUseStatus(useStatus);
			changeHistory.setOrderId(history.getOrderId());
			changeHistorys.add(changeHistory);
		}
		if (! CollectionUtils.isEmpty(changeHistorys)) {
			this.updateBatchById(changeHistorys);
			smsCouponHistoryMapper.saveOrderCouponRecord(changeHistorys);
		}
	}
}
